<?php

namespace app\demo\service\user_demo;

use app\demo\enum\Grade;
use app\demo\enum\Hobby;
use app\demo\enum\Sex;
use app\demo\enum\State;
use app\demo\model\User as UserModel;
use app\demo\model\InterestCate as InterestCateModel;

final class All {

    /**
     * @var UserModel
     */
    private $userModel;

    /**
     * @var InterestCateModel
     */
    private $interestCateModel;

    /**
     * @return UserModel
     */
    public function getUserModel(): UserModel {
        if (!$this->userModel) $this->setUserModel();
        return $this->userModel;
    }

    /**
     * @param UserModel $userModel
     */
    public function setUserModel(UserModel $userModel = null): void {
        $this->userModel = $userModel ?: (new UserModel());
    }

    /**
     * @return InterestCateModel
     */
    public function getInterestCateModel(): InterestCateModel {
        if (!$this->interestCateModel) $this->setInterestCateModel();
        return $this->interestCateModel;
    }

    /**
     * @param InterestCateModel $interestCateModel
     */
    public function setInterestCateModel(InterestCateModel $interestCateModel = null): void {
        $this->interestCateModel = $interestCateModel ?: (new InterestCateModel());
    }

    private static $instance;

    public static function getInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Notes: 列表筛选条件where集合
     * Author: Uncle-L
     * Date: 2021/11/15
     * Time: 12:02
     * @param array $filter
     * @return array
     */
    private function listWhere(array $filter): array {
        $ids = $filter['ids'];
        $name = $filter['name'];
        $where = [];
        if ($ids) $where[] = ['id', 'in', $ids];
        if ($name) $where[] = ['name', 'like', "%{$name}%"];
        return $where;
    }

    /**
     * Notes: 数量
     * Author: Uncle-L
     * Date: 2021/11/14
     * Time: 13:50
     * @param array $filter [筛选条件]
     * @return int
     */
    public function count(array $filter): int {
        $where = $this->listWhere($filter);
        return $this->getUserModel()->getOwnCount($where);
    }

    /**
     * Notes: 数据项
     * Author: Uncle-L
     * Date: 2021/11/15
     * Time: 12:05
     * @param int $limitStart
     * @param int $limitLength
     * @param array $filter
     * @param array $sort
     * @return array
     */
    public function items(int $limitStart, int $limitLength, array $filter, array $sort): array {
        $where = $this->listWhere($filter);
        $order = $sort + ['id' => 'desc'];
        $items = $this->getUserModel()->getOwnRows($where, ["*"], $order, $limitStart, $limitLength);
        foreach ($items as &$v) {
            $v['area'] = ['province' => $v['province'], 'city' => $v['city'], 'district' => $v['district']];
        }
        return $items;
    }

    /**
     * Notes: 获取所有兴趣分类数据项
     * Author: Uncle-L
     * Date: 2021/11/15
     * Time: 11:52
     * @return array
     */
    public function getAllInterestCateItems(): array {
        static $items;
        if (!$items) $items = $this->getInterestCateModel()->getOwnRows();
        return $items;
    }

    /**
     * Notes: 获取兴趣分类id和name的数组
     * Author: Uncle-L
     * Date: 2021/11/15
     * Time: 11:51
     * @return array
     */
    public function getInterestCateIdNameOptions(): array {
        static $options;
        if (!$options) {
            $items = $this->getAllInterestCateItems();
            $options = array_combine(array_column($items, "id"), array_column($items, "name"));
        }
        return $options;
    }

    /**
     * Notes: 数据获取
     * Author: Uncle-L
     * Date: 2021/11/16
     * Time: 10:45
     * @param int|null $id
     * @return array
     */
    public function load(int $id = null): array {
        $id = $id ?: input("get.id/d");
        $data = $this->getUserModel()->getOwnRow([
            ["id", "eq", $id],
            ["state", "neq", State::DELETED],
        ]);
        if (!$data) return [];
        $data['area'] = ['province' => $data['province'], 'city' => $data['city'], 'district' => $data['district']];
        return $data;
    }

    /**
     * Notes: 表单提交
     * Author: Uncle-L
     * Date: 2021/11/15
     * Time: 17:39
     * @param array $data
     * @param false $isEdit
     * @return bool
     */
    public function submit(array $data, $isEdit = false): bool {
        $saveData = [
            'avatar' => $data['avatar'],
            'name' => $data['name'],
            'sex' => $data['sex'],
            'age' => $data['age'],
            'grade' => $data['grade'],
            'hobby' => $data['hobby'] ? implode(',', $data['hobby']) : "",
            'province' => $data['area'] && isset($data['area']['province']) ? $data['area']['province'] : '',
            'city' => $data['area'] && isset($data['area']['city']) ? $data['area']['city'] : '',
            'district' => $data['area'] && isset($data['area']['district']) ? $data['area']['district'] : '',
            'intro' => $data['intro'],
            'interest_cate_ids' => $data['interest_cate_ids'] ? json_encode($data['interest_cate_ids']) : '',
            'friend_ids' => $data['friend_ids'] ? json_encode($data['friend_ids']) : '',
            'color' => $data['color'],
            'album' => $data['album'] ? implode(',', $data['album']) : "",
            'document' => $data['document'] ? json_encode($data['document']) : '',
            'other_document' => $data['other_document'] ? json_encode($data['other_document']) : '',
        ];
        if ($isEdit) {
            $saveData["id"] = $data["id"];
            $res = $this->getUserModel()->change($saveData);
        } else {
            $res = $this->getUserModel()->addRow($saveData);
        }
        return !!$res;
    }

    /**
     * Notes: 用户下拉搜索
     * Author: Uncle-L
     * Date: 2021/11/15
     * Time: 17:47
     * @param array $param
     * @return array
     */
    public function userDropdownSearchOptions(array $param = []): array {
        $param = $param ?: input('get.');
        $ids = filter_sql($param['ids']);
        $keywords = filter_sql($param['keywords']);

        $where = [];
        if ($ids) $where[] = ['id', 'in', $ids];
        if ($keywords) $where[] = ['name', 'like', "%{$keywords}%"];
        $field = ['id', 'name'];
        $datas = $this->getUserModel()->getOwnRows($where, $field, ["id" => "desc"], 0, 20);
        $items = array_combine(array_column($datas, "id"), array_column($datas, "name"));
        return $items;
    }

    /**
     * 数据导入多行处理
     * @param array $rowsData
     * @return mixed
     */
    public function rows(array $rowsData) {
        $datas = [];
        foreach ($rowsData as $id => $data) {
            $rowData = $data["row"];
            $datas[] = [
                    "name" => $rowData["name"],
                    "sex" => Sex::getValueByTitle($rowData["sex"]),
                    "age" => $rowData["age"],
                    "grade" => Grade::getValueByTitle($rowData["grade"]),
                    "hobby" => Hobby::getValueByTitle($rowData["hobby"]),
                    "intro" => $rowData["intro"],
                ] + $data["row"];
        }
        $this->getUserModel()->addRows($datas);
    }

}